//
//  PuzzleViewController.m
//  ImageAnimation
//
//  Created by apple on 5/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DraggableView.h"
#import "FixFrame.h"
#import "StartViewController.h"
#import "PuzzleViewController.h"
#import "MovingCommand.h"

@interface PuzzleViewController (){
    
    __unsafe_unretained IBOutlet UIButton *messUpButton;
    __unsafe_unretained IBOutlet UIButton *resetButton;
}

@property (nonatomic,retain) DraggableView *lastMovedDraggableView;
@property (nonatomic,retain) DraggableView *bulgeDraggableView;
@end

@implementation PuzzleViewController
@synthesize columnsCount;
@synthesize rowsCount;
@synthesize clearFixFrame;
@synthesize startViewController;
@synthesize lastMovedDraggableView=_lastMovedDraggableView;
@synthesize bulgeDraggableView=_bulgeDraggableView;
@synthesize movingCommand=_command;
@synthesize imageFromUser=_imageFromUser;
@synthesize heartsEmitter=_heartsEmitter;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    position = 0;
    CGRect wholeScreen = [[UIScreen mainScreen]bounds];
    //UIImage *image1 = [UIImage imageNamed:@"4.jpg"];
    UIImage *image2 = [UIImage imageNamed:@"2.jpg"];
    UIImage *defaultImage = image2;
    if (self.imageFromUser) {
        defaultImage = self.imageFromUser;
    }
    UIImage *imageForUse = [self setImageSize:defaultImage toSize:panelView.frame.size];

    if (CGRectGetHeight(wholeScreen) > CGRectGetWidth(wholeScreen)) {
        int height = wholeScreen.size.width;
        wholeScreen.size.width = wholeScreen.size.height;
        wholeScreen.size.height = height;
    }

    fixFrameArray = [[NSMutableArray alloc] init];
    array = [self devideImage:imageForUse];
    usedImagesArray = [[NSMutableArray alloc] initWithArray:array];
    self.bulgeDraggableView = usedImagesArray.lastObject;

    timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timerAnimation) userInfo:nil repeats:YES];
    
    self.movingCommand = [[MovingCommand alloc] init];
    
    [self initEmitter];
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (UIImage *)setImageSize:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (void)timerAnimation{
    [self runAnimation];
}

- (void)runAnimation{
    
    int count = [usedImagesArray count];
    if (position < rowsCount*columnsCount ) {
        
        CGRect frame = [self getFrameFromPosition:position];
        DraggableView *imageView = nil;
//        if (position == rowsCount*columnsCount - 1) {
//            imageView = [array lastObject];
//        }else{
//            imageView = [usedImagesArray objectAtIndex:rand()%count]; 
//        }
        imageView = [usedImagesArray objectAtIndex:position];
        [imageView setHorizontalIndex:position%columnsCount];
        [imageView setVerticalIndex:position/rowsCount];
        [imageView setFrame:frame];
        imageView.contentMode = UIViewContentModeCenter;
        [self.view addSubview:imageView];
//        [usedImagesArray removeObject:imageView];  
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [imageView setAlpha:1];
        //[imageView setFrame:CGRectMake(position*200, 0, 200, 200)];
        [UIView commitAnimations];
    }else{
        [self.bulgeDraggableView moveToTarget:self.clearFixFrame];
        messUpButton.enabled = YES;
        resetButton.enabled = YES;
        [timer invalidate];
    }
    position++;
}
- (NSMutableArray *)devideImage:(UIImage *)image{
    
    NSMutableArray *images = [NSMutableArray array];
    CGRect wholeScreen = [[UIScreen mainScreen]bounds];
    wholeScreen.size = panelView.frame.size;
    
    float columnNumber = LEVEL_NUMBER;
    float rowNumber = LEVEL_NUMBER;
    rowsCount = rowNumber;
    columnsCount = columnNumber;
    clearFixFrame = [[FixFrame alloc] initWithHorizontal:columnsCount andVertical:rowsCount-1];
    
    for (int v = 0 ; v < rowNumber; v++) {
        NSMutableArray *horizontalArray = [NSMutableArray arrayWithCapacity:columnNumber];
        [fixFrameArray addObject:horizontalArray];
    }
    float interval = 0;// pix
    float width = (CGRectGetWidth(wholeScreen) - (columnNumber + 1)*interval)/(columnNumber);
    
    float height = (CGRectGetHeight(wholeScreen) - (rowNumber + 1)*interval)/(rowNumber);
    CGRect defaultFixFrame = CGRectMake(columnsCount*(width + interval) + interval, (rowsCount- 1)*(height + interval) + interval, width, height);
    [clearFixFrame setFixFrameValue:defaultFixFrame];
    CGRect menuFrame = CGRectMake(columnsCount*(width + interval) + interval, 0, width, (rowsCount- 1)*(height + interval) + interval);
    menuView = [[UIView alloc] initWithFrame:menuFrame];
    [menuView setBackgroundColor:[UIColor grayColor]];
    //[self.view addSubview:menuView];
    UIButton *back = [[UIButton alloc] initWithFrame:menuView.bounds];
    [back setTitle:@"Back" forState:UIControlStateNormal];
    [back.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [back addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchDragInside];
    //[menuView addSubview:back];
    //image
    for (float i=0;i<rowNumber;i++) {
        for (float j=0;j<columnNumber;j++) {
            CGRect subFrame = CGRectMake(j*(width + interval) + interval, i*(height + interval) + interval, width, height);
            UIImage *partImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], subFrame)];
            DraggableView *imageView = [[DraggableView alloc] initWithFrame:subFrame];
            [imageView setTargetHorizontalIndex:j];
            [imageView setTargetVerticalIndex:i];
            [imageView setController:self];
            [imageView setImage:partImage];
            imageView.userInteractionEnabled = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
            [imageView setAlpha:0];
            [images addObject:imageView];
            
            
            FixFrame *fixFrame = [[FixFrame alloc] initWithHorizontal:j andVertical:i];
            [fixFrame setFixFrameValue:subFrame];
            [fixFrame setDraggableView:imageView];
            
            NSMutableArray *horizontalArray = [fixFrameArray objectAtIndex:i];
            [horizontalArray insertObject:fixFrame atIndex:j];
        }
    }
    return images;
}

- (void)draggableViewDidMove{
    for (DraggableView *each in usedImagesArray) {
        if (!each.isRightPosition) {
            return;
        }
    }
    
    [self.movingCommand clearMovingCommand];
    //
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Win" message:@"Win!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [self youWin];
}

- (void)viewDidUnload
{
    panelView = nil;
    resetButton = nil;
    messUpButton = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        return YES;
    }
    return NO;
}

- (FixFrame *)findFixFrameHorizontal:(NSInteger)h andVertical:(NSInteger)v{
    //    NSLog(@"clear (h,v) = (%d,%d)",self.clearFixFrame.horizontalIndex,self.clearFixFrame.verticalIndex);
    if (h == self.clearFixFrame.horizontalIndex && v == self.clearFixFrame.verticalIndex) {
        return self.clearFixFrame;
    } 
    return nil;
}

- (DraggableView *)findDraggableViewByHorizontal:(NSInteger)h andVertical:(NSInteger)v{
    for (DraggableView *view in usedImagesArray) {
        if (h == view.horizontalIndex && v == view.verticalIndex ) {
            return view;
        } 
    }
    return nil;
}

- (CGRect)getFrameFromHorizontal:(NSInteger)h andVertical:(NSInteger)v{
    NSArray *horizontalArray = [fixFrameArray objectAtIndex:v];
    if (horizontalArray) {
        FixFrame *target = [horizontalArray objectAtIndex:h];
        return target.fixFrameValue;
    }   
    return CGRectMake(0, 0, 0, 0);
}

- (CGRect)getFrameFromPosition:(NSInteger)p{
    int v = p/rowsCount;
    int h = p%columnsCount;
    return [self getFrameFromHorizontal:h andVertical:v];
}

- (IBAction)messUpImagesInThePanel:(id)sender {
    
    if (self.clearFixFrame.horizontalIndex == LEVEL_NUMBER&&
        self.clearFixFrame.verticalIndex == LEVEL_NUMBER - 1) {
        DraggableView *draggableView = [self findDraggableViewByHorizontal:LEVEL_NUMBER-1 andVertical:LEVEL_NUMBER-1];
        if (draggableView){
            [draggableView moveToTarget:self.clearFixFrame];
            self.lastMovedDraggableView = draggableView;
            //[self.movingCommand addDirection:MovingDirectionLeft];
        }
    }
    
    for (int i = 0; i < 10; i++) {
        [self moveByNextDirection];
    }
    
}
- (IBAction)resetImagesInThePanel:(id)sender {
    [self moveByPreviousDirection];
    if (self.movingCommand.canMoveToPreiousDriection) {
        [self performSelector:@selector(resetImagesInThePanel:) withObject:nil afterDelay:0.1];
    }

}

- (void)moveByNextDirection{
    MovingDirection movingDirection = self.movingCommand.getNextDirection;
    FixFrame *random = [self.clearFixFrame getFixFrameByMovingDirection:movingDirection];
    DraggableView *draggableView = [self findDraggableViewByHorizontal:random.horizontalIndex andVertical:random.verticalIndex];
    if (draggableView && draggableView != self.lastMovedDraggableView && draggableView != self.bulgeDraggableView) {
        [draggableView moveToTarget:self.clearFixFrame];
        self.lastMovedDraggableView = draggableView;
        [self.movingCommand addDirection:movingDirection];
        resetButton.enabled = YES;
    } else {
        [self performSelector:@selector(moveByNextDirection)];
    }
}

- (void)moveByPreviousDirection{
    MovingDirection movingDirection = self.movingCommand.getPreviousDirection;
    FixFrame *random = [self.clearFixFrame getFixFrameByMovingDirection:movingDirection];
    DraggableView *draggableView = [self findDraggableViewByHorizontal:random.horizontalIndex andVertical:random.verticalIndex];
    if (draggableView && draggableView != self.bulgeDraggableView) {
        [draggableView moveToTarget:self.clearFixFrame];
        self.lastMovedDraggableView = draggableView;
    }
}

- (void)moveAnimaiton:(DraggableView *)draggableView withFrame:(CGRect)frame{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.2];
    [draggableView setFrame:frame];
    [UIView commitAnimations];
}


-(UIImage*)resizedImage:(UIImage*)inImage  inRect:(CGRect)thumbRect {
    
    UIGraphicsBeginImageContext(thumbRect.size);
    [inImage drawInRect:thumbRect];
    return UIGraphicsGetImageFromCurrentImageContext();
    
    
    
}

- (IBAction)clickBack:(id)sender{
    [self.startViewController dismissModalViewControllerAnimated:YES]; 
}


- (void)youWin{
    
/*
	// Fires up some hearts to rain on the view
	CABasicAnimation *heartsBurst = [CABasicAnimation animationWithKeyPath:@"emitterCells.heart.birthRate"];
	heartsBurst.fromValue		= [NSNumber numberWithFloat:100.0];
	heartsBurst.toValue			= [NSNumber numberWithFloat:  0.0];
	heartsBurst.duration		= 5.0;
	heartsBurst.timingFunction	= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
	[self.view.layer addSublayer:self.heartsEmitter];
	[self.heartsEmitter addAnimation:heartsBurst forKey:@"heartsBurst"]; 
    
*/
}

- (void)initEmitter{
/*
    // Configure the particle emitter
	self.heartsEmitter = [CAEmitterLayer layer];
	self.heartsEmitter.emitterPosition = CGPointMake(1024/2, 
													 748/2);
	self.heartsEmitter.emitterSize = CGSizeMake(102, 100);
	
	// Spawn points for the hearts are within the area defined by the button frame
	self.heartsEmitter.emitterMode = kCAEmitterLayerVolume;
	self.heartsEmitter.emitterShape = kCAEmitterLayerRectangle;
	self.heartsEmitter.renderMode = kCAEmitterLayerAdditive;
	
	// Configure the emitter cell
	CAEmitterCell *heart = [CAEmitterCell emitterCell];
	heart.name = @"heart";
	
	heart.emissionLongitude = M_PI/2; // up
	heart.emissionRange =  M_PI;  // in a wide spread
	heart.birthRate		= 0.0;			// emitter is deactivated for now
	heart.lifetime		= 20.0;			// hearts vanish after 10 seconds
    
	heart.velocity		= -120;			// particles get fired up fast
	heart.velocityRange = 60;			// with some variation
	heart.yAcceleration = 20;			// but fall eventually
	
	heart.contents		= (id) [[UIImage imageNamed:@"DazHeart"] CGImage];
	heart.color			= [[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5] CGColor];
	heart.redRange		= 1;			// some variation in the color
	heart.blueRange		= 1;
    heart.greenRange    = 1;
	heart.alphaSpeed	= -0.5 / heart.lifetime;  // fade over the lifetime
	
	heart.scale			= 0.15;			// let them start small
	heart.scaleSpeed	= 0.2;			// but then 'explode' in size
	heart.spinRange		= 5.0 * M_PI;	// and send them spinning from -180 to +180 deg/s
	
	// Add everything to our backing layer
	self.heartsEmitter.emitterCells = [NSArray arrayWithObject:heart];
	[self.view.layer addSublayer:self.heartsEmitter];
*/
}
@end

